package com.superiron.scaffold.core.service.secure.service;

import com.superiron.scaffold.core.service.secure.support.DataAuthorityDetector;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.Map;

/**
 * 数据权限检测服务
 *
 * @author yzg
 * @date 2022年7月8日11:50:58
 */
@Slf4j
@Service
public class DataAuthorityDetectorServiceImpl implements DataAuthorityDetectorService, InitializingBean , ApplicationContextAware{
	
	/**
	 * 检测对象的服务
	 */
	private Map<String , DataAuthorityDetector> detectorMap = new HashMap<>();
	
	private ApplicationContext applicationContext ;
	
	/**
	 * 校验
	 *
	 * @param params
	 * @return
	 */
	@Override
	public boolean detect(String detectorName , Object[] params) {
		DataAuthorityDetector detector = detectorMap.get(detectorName) ;
		Assert.notNull(detector , detectorName + "对应的检测器不存在") ;
		return detectorMap.get(detectorName).detect(params) ;
	}
	
	/**
	 * 初始化加载系统服务
	 * @throws Exception
	 */
	@Override
	public void afterPropertiesSet() throws Exception {
		Map<String , DataAuthorityDetector> detectorSpringMap = applicationContext.getBeansOfType(DataAuthorityDetector.class) ;
		if(MapUtils.isNotEmpty(detectorSpringMap)){
			for(Map.Entry<String , DataAuthorityDetector> detectorBean : detectorSpringMap.entrySet()){
				detectorMap.put(detectorBean.getValue().getClass().getName() , detectorBean.getValue()) ;
			}
		}
	}
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext ;
	}
}
